/* eslint-disable */
<template>
  <div>
    <Card>
      <p slot="title" class="card-title">
        <Icon type="home"></Icon>
        <span>线索管理</span>
      </p>
      <div>
        <template>
          <Form ref="search" :model="search" :label-width="80">
            <FormItem label="关键字：" prop="name">
              <Input
                style="width: 400px"
                v-model="search.name"
                placeholder="姓名或者手机号码"
                class="margin-bottom-10"
              ></Input>
            </FormItem>
            <FormItem label="分配状态：" prop="status">
              <RadioGroup v-model="search.status" type="button" size="large">
                <Radio label="All">全部</Radio>
                <Radio label="N">未分配</Radio>
                <Radio label="Y">已分配</Radio>
              </RadioGroup>
            </FormItem>
            <Row>
              <Col span="4">
                <FormItem label="导入时间:" prop="startDate">
                  <DatePicker
                    format="yyyy-MM-dd"
                    type="date"
                    placeholder="开始时间"
                    :editable="false"
                    v-model="search.startDate"
                    @on-change="search.startDate=$event"
                    :options="endDateoptions"
                  ></DatePicker>
                </FormItem>
              </Col>
              <Col span="4">
                <FormItem :label-width="0" prop="endDate">
                  <DatePicker
                    format="yyyy-MM-dd"
                    type="date"
                    placeholder="结束时间"
                    v-model="search.endDate"
                    @on-change="search.endDate=$event"
                    :editable="false"
                    style="margin-left:10px;"
                    :options="endDateoptions"
                  ></DatePicker>
                </FormItem>
              </Col>
            </Row>

            <FormItem>
              <Button type="primary" @click="getClueList()">查詢</Button>
              <Button style="margin-left: 8px" @click="reset('search');">重置</Button>
            </FormItem>
          </Form>
        </template>
      </div>
    </Card>
    <Card>
      <div style="text-align:right">
        <template>
          <Button
            :disabled="!currentGroup.id"
            shape="circle"
            icon="ios-cloud-upload-outline"
            @click="uploadModal=true"
          >导入线索</Button>
          <Button
            :disabled="selectIds.length<=0"
            shape="circle"
            icon="ios-search"
            @click="deleteClue ('1')"
          >删除</Button>
          <Button
            shape="circle"
            :disabled="!currentGroup.id"
            :loading="deleteArrLoading"
            icon="ios-search"
            @click="deleteClue ('2')"
          >删除组数据</Button>
          <Button :disabled="!currentGroup.id" @click="openAssigenModal()" shape="circle">分配</Button>
          <Button shape="circle" :disabled="!currentGroup.id" @click="checkDuplicate()" :loading="checkDuplicateLoading" >查重</Button>
        </template>
      </div>
    </Card>
    <Card>
      <div style="height:600px;">
        <template>
          <div class="demo-split" style="height:100%">
            <Split v-model="split1">
              <div slot="left" class="demo-split-pane">
                <p slot="title">我的分组 
                  <Icon  v-if="treePageNo<=treeTotalPages" @click="nextPageClueGroup()" style="font-size:20px;cursor: pointer;margin-left:10px;"type="md-fastforward" />
                  <Icon   v-if="treePageNo>treeTotalPages" style="font-size:20px;margin-left:10px;" type="ios-fastforward-outline" />
                  
                  </p>


                <template>
                  <Scroll height="450" :on-reach-bottom="handleReachBottom">
                    <Tree :data="data5" :render="renderContent"></Tree>
                  </Scroll>
                </template>
              </div>
              <div slot="right" class="demo-split-pane">
                <p
                  slot="title"
                  style="margin-bottom: 10px;"
                >我的线索{{currentGroup.groupName?"----"+currentGroup.groupName:""}}</p>
                <template>
                  <Table
                    stripe
                    :columns="columns1"
                    :data="clueData.data"
                    style="height:520px"
                    @on-selection-change="tableSelectionChange"
                    @on-select-all="tableSelectionChange"
                    @on-select-all-cancel="tableSelectionChange"
                  >
                    <template slot-scope="{ row }" slot="assignedAt">
                      <strong>{{ row.assignedAt?"已分配":"未分配" }}</strong>
                    </template>
                    <template slot-scope="{ row }" slot="gender">{{ row.gender?row.gender.name:"" }}</template>
                  </Table>
                  <Page
                    :total="clueData.total"
                    size="small"
                    show-total
                    show-elevator
                    class="tr"
                    @on-change="pageChange"
                    :current.sync="clueData.current"
                    :page-size="clueData.size"
                  ></Page>
                </template>
              </div>
            </Split>
          </div>
        </template>
      </div>
    </Card>
    <template>
      <Modal v-model="editModal" title="编辑分组" @on-ok="editGroup" @on-cancel="close('editModal')">
        <Form :model="editGroupData" :label-width="80">
          <FormItem label="分组名称">
            <Input type="text" v-model="editGroupData.groupName" placeholder="分组名称"></Input>
          </FormItem>
        </Form>
      </Modal>
    </template>
    <template>
      <Modal
        v-model="createModal"
        title="新建分组"
        @on-ok="createClueGroup"
        @on-cancel="close('createModal')"
      >
        <Form :model="createGroup" :label-width="80">
          <FormItem label="分组名称">
            <Input type="text" v-model="createGroup.name" placeholder="分组名称"></Input>
          </FormItem>
        </Form>
      </Modal>
    </template>
    <Upload v-if="uploadModal" :currentGroup="currentGroup" @uploadSuccess="uploadSuccess"  @cancel="onModalCancel"></Upload>
    <Assigne
      v-if="assigneModalFlag"
      :group="currentGroup"
      :assigneRes="assigneRes"
      @cancel="onModalCancel"
    />
  </div>
</template>
<style>
.demo-split {
  height: 200px;
  border: 1px solid #dcdee2;
}
.demo-split-pane {
  padding: 10px;
}
.treeSpan:hover {
  background: #e7f4f9;
}
.uploadTips a:after {
  content: "\F3F2";
  font-family: Ionicons;
  color: #aaa;
  margin-left: 3px;
}
</style>
<script>
import Assigne from "./components/assigne.vue";
import Upload from "./components/upload.vue";
export default {
  data() {
    return {
      split1: 0.3,
      search: {},
      createGroup: {},
      assigneModalFlag: false,
      uploadModal: false,
      columns1: [
        {
          type: "selection",
          width: 60,
          align: "center"
        },
        { title: "客户名称", key: "name" },
        { title: "性别", slot: "gender" },
        { title: "电话号码", key: "phone" },
        { title: "分配状态", slot: "assignedAt" },
        { title: "导入时间", key: "createdAt" }
      ],
      clueData: this.initTableData(),
      data5: [
        {
          groupName: "我的分组",
          expand: true,
          render: (h, { root, node, data }) => {
            return h(
              "span",
              {
                style: {
                  display: "inline-block",
                  width: "100%",
                  fontWeight: 900
                }
              },
              [
                h("span", data.groupName),
                h(
                  "span",
                  {
                    style: {
                      display: "inline-block",
                      float: "right",
                      marginRight: "32px",
                      fontSize: "21px",
                      cursor: "pointer"
                    }
                  },
                  [
                    h("Icon", {
                      props: Object.assign({}, this.ionProps, {}),
                      on: {
                        click: () => {
                          this.openCreateGroup();
                        }
                      }
                    })
                  ]
                )
              ]
            );
          },
          children: []
        }
      ],
      ionProps: {
        type: "ios-add-circle-outline"
      },
      deleteProps: {
        type: "ios-remove-circle-outline"
      },
      editProps: {
        type: "ios-create-outline"
      },
      editModal: false,
      currentGroup: {},
      editGroupData: {},
      createModal: false,
      treePageNo: 1,
      treeTotalPages: 1,
      uploadHead: {
        token: localStorage.getItem("token")
      },
      uploadModal: false,
      uploadUrl: this.getBaseUrl() + "/clue/uploadFile",
      selectIds: [],
      checkDuplicateLoading:false,
      deleteArrLoading:false,
      endDateoptions: {
        disabledDate(date) {
          return date && date.valueOf() > Date.now();
        }
      },
      assigneRes: {},
      getClueGroupLoading:false
      // selectClass:"treeSpan ivu-tree-title-selected"
    };
  },
  methods: {
    renderContent(h, { root, node, data }) {
      return h(
        "span",
        {
          style: {
            display: "inline-block",
            width: "100%"
          },
          class: data.selectClass
          //   on: {
          //     click: () => {
          //       return this.OnSelectChange(root, node, data);
          //     }
          //   }
        },
        [
          h(
            "span",
            {
              style: {
                fontWeight: 900,
                cursor: "pointer",
                width: "55%",
                display: "inline-block"
              },
              on: {
                click: () => {
                  this.OnSelectChange(root, node, data, false);
                }
              }
            },
            data.groupName
          ),
          h(
            "span",
            {
              style: {
                display: "inline-block",
                float: "right",
                marginRight: "32px",
                fontSize: "21px",
                cursor: "pointer"
              }
            },
            [
              h("Icon", {
                props: Object.assign({}, this.editProps, {}),
                on: {
                  click: () => {
                    this.OnSelectChange(root, node, data, true);
                  }
                }
              }),
              h("Icon", {
                props: Object.assign({}, this.deleteProps, {}),
                on: {
                  click: () => {
                    this.removeGroup(root, node, data);
                  }
                }
              })
            ]
          )
        ]
      );
    },
    initTableData() {
      return {
        data: [],
        current: 1,
        size: 10
      };
    },
    handleReachBottom() {
      return new Promise(resolve => {
          this.nextPageClueGroup();
        resolve();
      });
    },
    pageChange() {
      if (this.clueData.current > this.clueData.totalPages) {
        this.$Message.error({
          content: "填入页数超出最大页数",
          duration: 3,
          closable: true
        });
      } else {
        this.getClueList();
      }
    },
    nextPageClueGroup(){
        if (this.treePageNo <= this.treeTotalPages) {
          this.getClueGroup();
        }
    },
    editGroup() {
      var url = "/clue/group/edit";

      this.post(url, this.editGroupData).then(res => {
        if (this.checkIsSsuccess(res)) {
          this.treePageNo = 1;
          this.treeTotalPages = 1;
          this.data5[0].children = [];
          this.$Message.success({
            content: "编辑成功！",
            duration: 1,
            closable: true,
            onClose: () => this.getClueGroup()
          });
        } else {
          this.$Message.error({
            content: res["msg"],
            duration: 3,
            closable: true
          });
        }
      });
    },
    OnSelectChange(root, node, data, flag) {
      //  this.selectClass = "treeSpan";
      if (!flag) {
        if (data.id == this.currentGroup.id) {
          this.currentGroup = {};
          data.selectClass = "treeSpan ";
        } else {
          this.currentGroup = Object.assign({}, data);
          //点击edit
          data.selectClass = "treeSpan ivu-tree-title-selected";
          root.forEach(k => {
            if (k.nodeKey == 0) {
            } else if (k.node.nodeKey == node.nodeKey) {
              data.selectClass = "treeSpan ivu-tree-title-selected";
            } else {
              k.node.selectClass = "treeSpan";
            }
          });
        }
        this.clueData = this.initTableData();
        this.getClueList();
      } else {
        this.editGroupData = Object.assign({}, data);
      }
      this.editModal = flag;
    },
    openCreateGroup() {
      this.createModal = true;
    },
    close(type) {
      this[type] = false;
    },
    getClueGroup() {
        this.getClueGroupLoading = true;
      let res = this.post(
        "/clue/group/{pageNo}",
        {},
        { pageNo: this.treePageNo }
      
      ).then(res => {
          this.getClueGroupLoading = false;
        if (this.checkIsSsuccess(res)) {
          this.treeTotalPages = res.data.totalPages;
          if (res.data.content && res.data.content.length > 0) {
            res.data.content.forEach(k => {
              k.selectClass = "treeSpan";
              this.data5[0].children.push(k);
            });
          }
          this.treePageNo++;
        } else {
          this.$Message.error({
            content: res["msg"],
            duration: 3,
            closable: true
          });
        }
      });
    },
    createClueGroup() {
      var url = "/clue/group/create";
      this.post(url, this.createGroup).then(res => {
        if (this.checkIsSsuccess(res)) {
          this.treePageNo = 1;
          this.treeTotalPages = 1;
          this.data5[0].children = [];
          this.$Message.success({
            content: "创建成功！",
            duration: 1,
            closable: true,
            onClose: () => this.getClueGroup()
          });
        } else {
          this.$Message.error({
            content: res["msg"],
            duration: 3,
            closable: true
          });
        }
      });
    },
    removeGroup(root, node, data) {
      this.$Modal.confirm({
        title: "提示:",
        width: 300,
        content:
          "<p>確定移除分組:" +
          data.groupName +
          "</p>(移除分组不会删除分组下所有线索)",
        onOk: () => {
          var url = "/clue/group/delete/{id}";
          this.post(url, {}, { id: data.id }).then(res => {
            if (this.checkIsSsuccess(res)) {
              this.treePageNo = 1;
              this.treeTotalPages = 1;
              this.data5[0].children = [];
              this.currentGroup = {};
              this.$Message.success({
                content: "刪除成功！",
                duration: 1,
                closable: true,
                onClose: () => {
                  this.currentGroup = {};
                  this.getClueGroup();
                  this.clueData = this.initTableData();
                  this.getClueList();
                }
              });
            } else {
              this.$Message.error({
                content: res["msg"],
                duration: 3,
                closable: true
              });
            }
          });
        },
        onCancel: () => {}
      });
    },
    uploadSuccess() {
      this.uploadModal = false;
      this.clueData = this.initTableData();
      this.getClueList();
    },
    getClueList() {
      var url = "/clue/query/{pageNo}";
      var ps = {
        groupId: this.currentGroup.id ? "" + this.currentGroup.id : ""
      };

      ps = Object.assign(ps, this.search);
      this.selectIds = [];

      this.post(url, ps, { pageNo: this.clueData.current }).then(res => {
        this.checkDuplicateLoading = false;
            this.deleteArrLoading = false;
        if (this.checkIsSsuccess(res)) {
          this.clueData.data = res.data.content;
          this.clueData.total = res.data.totalElements;
          this.clueData.totalPages = res.data.totalPages;
        } else {
          this.$Message.error({
            content: res["msg"],
            duration: 3,
            closable: true
          });
        }
      });
    },
    checkDuplicate() {
      var url = "/clue/checkDuplicate/{groupId}";
      this.checkDuplicateLoading = true;
      this.post(url, {}, { groupId: this.currentGroup.id }).then(res => {
        if (this.checkIsSsuccess(res)) {
          var msg = "查重完成。已去重" + res.data.count + "条。";
          this.$Message.success({
            content: msg,
            duration: 2,
            closable: true,
            onClose: () => {
              this.clueData = this.initTableData();
              this.getClueList();
            }
          });
        } else {
          this.$Message.error({
            content: res["msg"],
            duration: 3,
            closable: true
          });
        }
      });
    },
    deleteClue(type) {
      this.$Modal.confirm({
        title: "提示:",
        width: 300,
        content: "<p>確定刪除线索?</p>",
        onOk: () => {
          var groupId = "2" == type ? this.currentGroup.id : 0;
          var ids;
          var ps = {
            ids: this.selectIds,
            groupId: groupId
          };
          if('2'==type){
              this.deleteArrLoading = true;
          }
          var url = "/clue/delete";
          this.post(url, ps, {}).then(res => {
            if (this.checkIsSsuccess(res)) {
              this.$Message.success({
                content: "删除成功!共删除:" + res["data"] + "条",
                duration: 2,
                closable: true,
                onClose: () => {
                  this.clueData = this.initTableData();
                  this.getClueList();
                  if ("2" == type) {
                    this.selectIds = [];
                  } else {
                    this.currentGroup = {};
                  }
                }
              });
            } else {
              this.$Message.error({
                content: res["msg"],
                duration: 3,
                closable: true
              });
            }
          });
        }
      });
    },
    tableSelectionChange(selection) {
      this.selectIds = [];
      selection.forEach(k => {
        this.selectIds.push(k.id);
      });
    },
    reset(name) {
      this.$refs[name].resetFields();
    },
    onModalCancel(obj) {
      // this.assigneModalFlag = false;
      this[obj.name]= false;
      if(obj.refresh){
        this.getClueList();
      }
    },
    openAssigenModal() {
      var url = "/clue/assigne/{groupId}";
      var ps = {
        groupId: this.currentGroup.id
      };
      this.post(url, {}, ps).then(res => {
        if (this.checkIsSsuccess(res)) {
          this.assigneRes = res.data;
          this.assigneModalFlag = true;
        } else {
          this.$Message.error({
            content: res["msg"],
            duration: 3,
            closable: true
          });
        }
      });
    }
  },
  created: function() {
    this.getClueGroup();
    this.getClueList();
  },
  components: {
    Assigne,
    Upload
  }
};
</script>